// 导入路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
// 使用路由
Vue.use(VueRouter)
import store from '@/store'
// 保存VueRouter原型
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
// 重写push和replace方法
// 参数1：告诉往哪里跳转，参数2：成功。参数3：失败
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    // call || apply 都可以调用函数一次，都可以篡改上下文一次
    // call || apply 传递参数。 call传参有，隔开，apply传递数组
    originPush.call(this, resolve, reject)
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}
// 配置路由
let router = new VueRouter({
  routes,
  scrollBehavior(to, from, savePosition) {
    return {
      y: 0,
    }
  },
})
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token
  let name = store.state.user.userInfo.name
  // 登录
  if (token) {
    if (to.path == '/login') {
      next('/home')
    } else {
      if (name) {
        next()
      } else {
        try {
          // 获取信息成功
          await store.dispatch('getUserInfo')
          next()
        } catch (error) {
          // token失效了获取不到用户信息，重新登录，清除token
          await store.dispatch('userLogout')
          next('/login')
        }
      }
    }
  } else {
    let toPath = to.path
    if (
      toPath.indexOf('/trade') != -1 ||
      toPath.indexOf('/pay') != -1 ||
      toPath.indexOf('/center') != -1
    ) {
      next('/login?redirect='+toPath)
    } else {
      next()
    }
  }
})
export default router
